package com.isolation.harassed.app;

import java.lang.ref.SoftReference;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import com.isolation.harassed.common.util.PlatformUtil;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.text.TextUtils;
import android.util.Log;

/**
 * Extension android.app.Application
 * 
 * @author allon
 */
public class App extends Application {

	private String UUID;
	private static App THIS;
	private static PackageInfo packageInfo;
	private HashMap<String, SoftReference<Activity>> taskMap;
	private static final String TAG = "com.isolation.harassed.app";

	@Override
	public void onCreate() {
		THIS = this;
//		com.baidu.mapapi.SDKInitializer.initialize(getApplicationContext());
//		com.activeandroid.ActiveAndroid.initialize(getApplicationContext());
//		com.ihakul.connector.client.SDKInitializer.initialize(getApplicationContext());
//		connector = new ServiceManager();
		taskMap = new LinkedHashMap<String, SoftReference<Activity>>();
	}

	/**
	 * 交由程序主进程托管当前的上下文活动对象
	 * 
	 * @param activity
	 *            上下文活动对象
	 */
	public void addActivity(Activity activity) {
		if (activity != null) {
			String className = activity.getClass().getName();
			if (!taskMap.containsKey(className)) {
				taskMap.put(className, new SoftReference<Activity>(activity));
			}
		}
	}

	/**
	 * 根据类名称从程序主进程获得上下文活动对象实例
	 * 
	 * @前置条件 该实例已调用{@link #addActivity(Activity)}由程序主进程托管
	 * @param mayActivity
	 *            类对象 ，{@link android.app.Activity#Activity Activity.class}
	 * @return target activity or null if Activity not exists and null
	 */
	public final Context findActivityByName(Class<?> mayActivity) {
		if (null == mayActivity) {
			return null;
		}
		String className = mayActivity.getClass().getName();
		Set<Entry<String, SoftReference<Activity>>> items = taskMap.entrySet();
		for (Map.Entry<String, SoftReference<Activity>> item : items) {
			SoftReference<Activity> activityReference = item.getValue();
			Activity activity = activityReference.get();
			String keyName = activity.getClass().getName();
			if (keyName.equals(className)) {
				return activity;
			}
		}
		return null;
	}

	/**
	 * 获得程序最顶层的Activity实例
	 * 
	 * @前置条件 该实例已调用{@link #addActivity(Activity)}由程序主进程托管
	 * @return history top Activity or ApplicationContext
	 */
	public final Context getTopActivity() {
		if (taskMap.size() > 0) {
			Iterator<String> keys = taskMap.keySet().iterator();
			String key = null;
			while (keys.hasNext()) {
				key = keys.next();
			}
			if (!TextUtils.isEmpty(key))
				return taskMap.get(key).get();
		}
		return getApplicationContext();
	}

	public final void removeActivity(String className) {
		taskMap.remove(className);
	}

	/**
	 * 根据自身包名，在Dalvik中查询程序自身的版本等信息
	 * 
	 * @return application packageInfo
	 */
	public final PackageInfo getPackageInfo() {
		PackageInfo localInfo = null;
		if (packageInfo == null) {
			try {
				PackageManager pm = getPackageManager();
				localInfo = pm.getPackageInfo(getPackageName(), 0);
			} catch (NameNotFoundException e) {
				e.printStackTrace();
			}
			packageInfo = localInfo;
		}
		return packageInfo;
	}

	/**
	 * 获取到服务端的请求及推送服务对象
	 * 
	 * @return {@link RemoteService}
	 */
/*	public RemoteService getConnector() {
		return this.connector;
	}*/

	/**
	 * 退出整个程序
	 */
	public final void exit() {
		Set<Entry<String, SoftReference<Activity>>> items = taskMap.entrySet();
		for (Map.Entry<String, SoftReference<Activity>> item : items) {
			SoftReference<Activity> activityReference = item.getValue();
			Activity activity = activityReference.get();
			if (activity != null && !activity.isFinishing()) {
				activity.finish();
			}
		}
		this.taskMap.clear();
		// System.exit(0);
		// Process.killProcess(Process.myPid());
	}

	public static App get() {
		return THIS;
	}

	/**
	 * 获得客户端识别ID
	 * 
	 * @return Device UUID
	 */
	public String getClientId() {
		if (TextUtils.isEmpty(this.UUID)) {
			this.UUID = PlatformUtil.getDeviceUUID(this);
		}
		return this.UUID;
	}

	@Override
	public void onTerminate() {
		Log.v(TAG, "isplc.trace.client.onTermiante()");
	}
}
